const path = require('path')
const Router = require('express').Router()
const { asyncHandle, getErr } = require('../util/util')

const multer = require('multer')
// const upload = multer({ dest: path.resolve(__dirname, '../public/upload/') })

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.resolve(__dirname, '../public/upload/'))
    },
    filename: function (req, file, cb) {
        // fieldname 字段名
        const ext = path.extname(file.originalname)
        const filename = file.fieldname + '-' + Date.now() + ext
        cb(null, filename)
    }
})

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 100 * 1024 // 限制上传文件大小
    },
    fileFilter(req, file, cb) {
        //验证文件后缀名
        const extname = path.extname(file.originalname);
        const whitelist = [".jpg", ".gif", "png"];
        if (whitelist.includes(extname)) {
            cb(null, true);
        } else {
            cb(new Error(`your ext name of ${extname} is not support`));
        }
    },
})

// 文件上传
Router.post('/', upload.single('file'), asyncHandle(async (req, res) => {
    return {
        url: '/upload/' + req.file.filename
    }
}))

module.exports = Router